package light.head.dao.el;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.cache.Cache;
import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.el.PaperTemplate;
@Service
public class PaperTemplateDAO extends BaseDAO<PaperTemplate, Integer>{
private final String sql_loadAll = "FROM PaperTemplate t WHERE t.deleted = 0";
	
	public RESULT findByMap(Integer oc, Map<String, String> map, PageBean pageBean){
		if(oc == null) return null;
		List<Object> list = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer("FROM PaperTemplate t WHERE t.oc = ?");
		list.add(oc);
		if(map != null){
			String name = map.get(Parm.NAME);
			String deleted = map.get(Parm.DELETED);
			
			if(isNotNull(name)){
				sql.append(" AND t.name LIKE ?");
				list.add("%" + name + "%");
			}
			if(isNotNull(deleted)){
				sql.append(" AND t.deleted = ?");
				list.add(Boolean.parseBoolean(deleted));
			}
		}
		
		sql.append(" ORDER BY t.code DESC");
		return findToPageBean(sql.toString(), pageBean, list);
	}

	
	public RESULT update(PaperTemplate temp){
		if(temp == null || temp.getCode() == null) return RESULT.ERROR;
		
		PaperTemplate old = get(temp.getCode());
		
		if(old == null) return RESULT.NOT_FIND;
		
		if(isNotNull(temp.getName()) && !temp.getName().equals(old.getName())){
			old.setName(temp.getName());
		}
		if(isNotNull(temp.getRemark()) && !temp.getRemark().equals(old.getRemark())){
			old.setRemark(temp.getRemark());
		}
		if(temp.getScore() != null && temp.getScore() != old.getScore()){
			old.setScore(temp.getScore());
		}
		if(temp.getDeleted() != null && temp.getDeleted() != old.getDeleted()){
			old.setDeleted(temp.getDeleted());
		}
		
		return upd(old);
	}
	
	public List<PaperTemplate> getAll(){
		if(null == Cache.tempList || Cache.tempList.size() == 0){
			loadAll();
		}
		return Cache.tempList;
	}
	
	public List<PaperTemplate> loadAll(){
		Cache.tempList = find(sql_loadAll);
		return Cache.tempList;
	}
}
